class Solution {
public:
    Node* connect(Node* root) {
        if (!root) return root;
        queue<Node *> q;
        q.push(root);
        while (!q.empty()) {
            Node *pre = nullptr;
            Node *cur = nullptr;
            int size = q.size();
            for (int i = 0; i < size; ++i) {
                cur = q.front();
                q.pop();
                if (pre) pre->next = cur;
                pre = cur;
                if (cur->left) q.push(cur->left);
                if (cur->right) q.push(cur->right);
            }
            cur->next = nullptr;
        }
        return root;
    }
};
